package com.whf.Controller;

import com.whf.constant.RedisConstant;
import com.whf.dataobject.SellerInfo;
import com.whf.enums.ResultEnum;
import com.whf.service.SellerService;
import com.whf.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/7/18 0018.
 */
@Controller
@Slf4j
@RequestMapping("/seller")
public class SellerUserController {
    @Autowired
    private SellerService sellerService;
    //redis操作模板
    @Autowired
    private StringRedisTemplate redisTemplate;
    //登陆
    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid,
                              HttpServletResponse response,
                              Map<String,Object> map){
        //1.openid查询数据库得到用户信息
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenId(openid);
        if(sellerInfo==null){
            log.info("[登陆]登陆出错,openid={}",openid);
            map.put("msg", ResultEnum.FAIL_LOGIN.getMessage());
            map.put("url","/sell/seller/product/list");
            return new ModelAndView("common/error",map);
        }
        //2.设置token到redis
        //生成token
        String token= UUID.randomUUID().toString();
        //设置过期时间
        Integer expire= RedisConstant.EXPIRE;

        //获得redis操作工具,key,value,过期时间,时间格式
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),openid,expire, TimeUnit.SECONDS);
        //3.设置token到cookie
        CookieUtil.set(response,"token",token,expire);
        return new ModelAndView("redirect:/seller/order/list");
    }
    //登出
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,
                               HttpServletResponse response,
                               Map<String,Object> map){
        //从cookie中获取token
        Cookie cookie = CookieUtil.get(request, "token");
        if(cookie!=null){
            //清除redis中的token
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
            //清楚cookie
            CookieUtil.set(response,"token",null,0);
        }
        map.put("msg",ResultEnum.SUCCESS_LOGOUT.getMessage());
        map.put("url","/sell/seller/order/list");
        return new ModelAndView("common/success",map);
    }
}
